using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;
using JiebaNet.Analyser;
using JiebaNet.Segmenter;
using JiebaNet.Segmenter.Common;
using Mvvm.Models;
using Mvvm.Services;
using ReactiveUI;
using LiveChartsCore;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using WordCloudSharp;
using System.Drawing;
using System.Text.RegularExpressions;
using Avalonia.Controls;
using Avalonia.Platform;
using EmotionChat.Services;
using LiveChartsCore.SkiaSharpView.Painting;
using Mvvm.Helpers;
using SkiaSharp;

namespace Mvvm.ViewModels;

public class ChatReportViewModel : PageViewModelBase
{
    public ISeries[] Series { get; set; } = [
        new ColumnSeries<int>(3, 4, 2),
        new ColumnSeries<int>(4, 2, 6),
        new ColumnSeries<double, DiamondGeometry>(4, 3, 4)
    ];
    
    private readonly IContentNavigationService _contentNavigationService;
    private readonly IChatDataStorage _chatDataStorage;
    private readonly IChatDataProcessedStorage _ChatDataProcessedStorage;

    // 用于存储user1的聊天高频词前十个对应的频数（已排序）
    private List<int> user1TopTenFrequentWordFreqs;
    // 用于存储user1的聊天高频词前十个对应的高频词（已排序，与频数一一对应）
    private List<string> user1TopTenFrequentWords;
    // 用于存储user2的聊天高频词前十个对应的频数（已排序）
    private List<int> user2TopTenFrequentWordFreqs;
    // 用于存储user2的聊天高频词前十个对应的高频词（已排序，与频数一一对应）
    private List<string> user2TopTenFrequentWords;
    
    public ChatReportViewModel(IChatDataStorage chatDataStorage, IChatDataProcessedStorage ChatDataProcessedStorage)
    {
       _chatDataStorage = chatDataStorage;
       _ChatDataProcessedStorage = ChatDataProcessedStorage;
       Init();
    }
    public async Task Init()
    {
        chatdatas = await _chatDataStorage.QueryAsync(1);
        chatProcessedDatas = await _ChatDataProcessedStorage.QueryAsync(1);
        //初次聊天时间
        firstchatDate = chatProcessedDatas[0].FirstChatTime;
        //获取报告双方用户名
        string userName1 = chatProcessedDatas[0].Username1;
        string userName2 = chatProcessedDatas[0].Username2;
        userName = userName1+"   &   "+userName2;
        TimeSpan diff_time = DateTime.Now - firstchatDate;
        
        // 可以根据需要进一步格式化时间差信息，例如将时间差转换为天、小时、分钟、秒等形式展示
        int days = diff_time.Days;
        int hours = diff_time.Hours;
        int minutes = diff_time.Minutes;
        int seconds = diff_time.Seconds;

        string formattedDiffTime = $"{days}天 {hours}小时 {minutes}分钟 {seconds}秒";
        
        //展示文字
        text1 = "我们第一次聊天是在：\n" +
                firstchatDate +
                "\n距今已经有:\n"+
                formattedDiffTime;
        
        //获取各类型消息数量
        PositiveMessageCount = chatProcessedDatas[0].PositiveMessageCount;
        NeutralMessageCount = chatProcessedDatas[0].NeutralMessageCount;
        NegativeMessageCount = chatProcessedDatas[0].NegativeMessageCount;
        PieSeries = new ISeries[]
        {
            new PieSeries<double> { Values = new double[] { PositiveMessageCount },Name = "积极",Fill = new SolidColorPaint(new SKColor(200, 200, 200))},
            new PieSeries<double> { Values = new double[] { NeutralMessageCount } ,Name = "中性"},
            new PieSeries<double> { Values = new double[] { NegativeMessageCount } ,Name = "消极"},
        };
        
        // 根据消息占比情况生成text2的内容
        int totalMessageCount = PositiveMessageCount + NeutralMessageCount + NegativeMessageCount;
        if (PositiveMessageCount > NeutralMessageCount && PositiveMessageCount > NegativeMessageCount)
        {
            text2 = "积极的氛围照亮了我们的交流之路，继续保持乐观，让温暖与希望常伴左右！";
        }
        else if (NeutralMessageCount > PositiveMessageCount && NeutralMessageCount > NegativeMessageCount)
        {
            text2 = "平稳的交流是我们关系的基石，保持平和心态，稳中求进，会让我们更加默契。";
        }
        else
        {
            text2 = "消极情绪有时会笼罩我们，但记住，冷静思考能驱散阴霾，少一点冲动，多一点理智，未来会更美好。";
        }
        //获取高频词及其频次
        user1_FrequentMessages = ParseHighFrequencyWords(chatProcessedDatas[0].User1HighFrequencyWords);
       
        user2_FrequentMessages = ParseHighFrequencyWords(chatProcessedDatas[0].User2HighFrequencyWords);

        var mostWord1 = user1_FrequentMessages.First();
        var mostWord2 = user2_FrequentMessages.First();
        
        text3 = "这段时间你们总共聊了" + chatProcessedDatas[0].TotalChatCount + "条消息\n共计" + chatProcessedDatas[0].TotalWordCount
                + "字\n" +userName1+"最喜欢说的词是:  "+mostWord1.Key+"  共说了"+mostWord1.Value+"次\n"
                +userName2+"也不遑多让，ta最喜欢说的词："+mostWord2.Key+"  共说了"+mostWord2.Value+"次";
           
        var sortedUser1 = user1_FrequentMessages.OrderByDescending(kvp => kvp.Value).Take(10).ToList();
        user1TopTenFrequentWordFreqs = sortedUser1.Select(kvp => kvp.Value).ToList();
        user1TopTenFrequentWords = sortedUser1.Select(kvp => kvp.Key).ToList();

        // 处理user2的高频词及频数，获取前十个并排序
        var sortedUser2 = user2_FrequentMessages.OrderByDescending(kvp => kvp.Value).Take(10).ToList();
        user2TopTenFrequentWordFreqs = sortedUser2.Select(kvp => kvp.Value).ToList();
        user2TopTenFrequentWords = sortedUser2.Select(kvp => kvp.Key).ToList();
       
        // 获取user1和user2实际的高频词数量
        int user1WordCount = user1TopTenFrequentWordFreqs.Count;
        int user2WordCount = user2TopTenFrequentWordFreqs.Count;

        // 取两者中较大值作为横坐标标签数量（可根据实际需求调整逻辑，如果想分别显示各自数量的标签则需分开处理）
        int maxWordCount = Math.Max(user1WordCount, user2WordCount);
        
        // 用于存储拼接后的横坐标标签
        List<string> xAxisLabels = new List<string>();

        for (int i = 0; i < maxWordCount; i++)
        {
            string label = "";
            if (i < user1WordCount)
            {
                label += user1TopTenFrequentWords[i];
            }
            if (i < user2WordCount)
            {
                if (label.Length > 0)
                {
                    label += "/";
                }
                label += user2TopTenFrequentWords[i];
            }
            xAxisLabels.Add(label);
        }
        
        // 直方图绘制
        histSeries = new ISeries[]
        {
            new ColumnSeries<double>
            {
                Name = userName1,
                Values = user1TopTenFrequentWordFreqs.Select(x => (double)x).ToArray(),
                Fill = new SolidColorPaint(SKColor.Parse("#FF0000"))
            },
            new ColumnSeries<double>
            {
                Name = userName2,
                Values = user2TopTenFrequentWordFreqs.Select(x => (double)x).ToArray(),
                Fill = new SolidColorPaint(SKColor.Parse("#0000FF"))
            }
        };
        
        XAxes = new Axis[]
        {
            new Axis
            {
                Labels = xAxisLabels.ToArray(),
                LabelsRotation = 30,
                SeparatorsPaint = new SolidColorPaint(new SKColor(200, 200, 200)),
                SeparatorsAtCenter = false,
                TicksPaint = new SolidColorPaint(new SKColor(35, 35, 35)),
                TicksAtCenter = true,
                // By default the axis tries to optimize the number of 
                // labels to fit the available space, 
                // when you need to force the axis to show all the labels then you must: 
                ForceStepToMin = true,
                MinStep = 1
            }
        };
    }
    
    
    
    public Dictionary<string, int> ParseHighFrequencyWords(string inputData)
    {
        Dictionary<string, int> frequencyDict = new Dictionary<string, int>();
        // 正则表达式模式，用于匹配 [高频词, 频次] 这样的格式
        string pattern = @"\[(.*?),\s*(.*?)\]";
        MatchCollection matches = Regex.Matches(inputData, pattern);
        foreach (Match match in matches)
        {
            string word = match.Groups[1].Value;
            if (int.TryParse(match.Groups[2].Value, out int frequency))
            {
                frequencyDict[word] = frequency;
            }
        }
        return frequencyDict;
    }
    
    public Dictionary<string, int> user1_FrequentMessages { get; set; }
    
    public Dictionary<string, int> user2_FrequentMessages { get; set; }
    public string text3 { get; set; }//页面三文本内容
    public ISeries[] histSeries { get; set; }
    public Axis[] XAxes { get; set; }
    public ISeries[] PieSeries { get; set; } //情绪类别占比饼图
    public static int PositiveMessageCount { set; get; } //积极消息数量
    public static int NeutralMessageCount { set; get; } //中性消息数量
    public static int NegativeMessageCount { set; get; } //消极消息数量
    public string userName
    {
        set;
        get;
    }
    public static List<ChatProcessedData> chatProcessedDatas
    {
        set;
        get;
    }
    public static List<ChatData> chatdatas
    {
        set;
        get;
    }
    public DateTime firstchatDate
    {
        get;
        set;
    }
    public string text1//我们第一次聊天是在------
    {
        get; set;
    }
    public string text2 { set; get; }//消极情绪有点太多了/你们的聊天很积极/

    public override bool CanNavigateNext 
    { 
        get => true;
        protected set => throw new NotSupportedException(); 
    }
    
    public override bool CanNavigatePrevious
    {
        get => true;
        protected set => throw new NotSupportedException();
    } 
}